import javax.swing.*;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * User: Ryan Green
 * Date: 2/10/11
 * Time: 2:12 PM
 * Copyright - University of South Australia
 */
public class LogHandler {
	BufferedWriter out;
	SimpleDateFormat formatter;
	String pattern = "dd.MM.yy hh:mm:ss";

	LogHandler(String filename) {
		try {
			formatter = new SimpleDateFormat(pattern);
			File f = new File(filename);
			if (!f.exists())f.createNewFile();
			out = new BufferedWriter(new FileWriter(filename, true));
		} catch (Exception e) {
			JOptionPane.showMessageDialog(null, "An error occurred when opening the log file.", "Error", JOptionPane.ERROR_MESSAGE);
			System.exit(0);
		}
	}

	void LogAndExit(String text){
		try{
			Log(text);
			out.close();
		} catch (Exception e){
			JOptionPane.showMessageDialog(null, "An error occurred when closing the log file.", "Error", JOptionPane.ERROR_MESSAGE);
		}
		System.exit(0);

	}

	void Log(String text){
		try{
			out.write(formatter.format(new Date()) + " " + text + "\n");
			out.flush();
		} catch (Exception e){
			JOptionPane.showMessageDialog(null, "An error occurred when writing to the log file.", "Error", JOptionPane.ERROR_MESSAGE);
		}
	}

	void Log(StackTraceElement[] elements){
		Log(ConvertStackTrace(elements));
	}

	void Log(String text, boolean disp){
		if (disp) JOptionPane.showMessageDialog(null, text, "Error", JOptionPane.ERROR_MESSAGE);
		Log(text);
	}

	void LogAndExit(StackTraceElement[] elements){
		LogAndExit(ConvertStackTrace(elements));
	}

	void LogAndExit(String text, boolean disp){
		if (disp) JOptionPane.showMessageDialog(null, text, "Error", JOptionPane.ERROR_MESSAGE);
		LogAndExit(text);
	}

	void Log(Exception e){
		Log(e.toString());
		Log(e.getStackTrace());
	}

	String ConvertStackTrace(StackTraceElement[] elements) {
		String text = "";
		for (StackTraceElement element: elements){
			text = text + "\n" + element.toString();
		}
		return text;
	}
}
